
import os
import logging
from logging import *
from .safe_log import SafeLog
import time



class LogUitl(object):

    def __init__(self):
        self.logger = None
        self.initialized = False
        self.base_path = ""
        self.log_prefix = ""

    @classmethod
    def instance(cls):
        if not hasattr(LogUitl, "_instance"):
            LogUitl._instance = LogUitl()
        return LogUitl._instance

    def init(self, base_path, log_prefix):
        self.initialized = True
        self.base_path = base_path
        self.log_prefix = log_prefix
        self.logger = self.define_process_logger(base_path, log_prefix)

    @classmethod
    def get_logger(cls) -> Logger:
        _instance = LogUitl.instance()
        if _instance.initialized is False:
            print("-----日志工具还没有初始化-----")
            return None
        return _instance.logger

    def define_process_logger(self, base_path, log_prefix):
        pid = os.getpid()

        # 日志父级文件夹
        parent_dir = base_path + "/logs/"

        logger_name = "%s_%s" % (log_prefix, pid)
        logger = logging.getLogger(logger_name)  # logger的名称
        logger.setLevel(logging.INFO)
        formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d %(levelname)s %(module)s: %(message)s',
                                      datefmt='%Y-%m-%d %H:%M:%S')
        # 输出到日志文件
        log_dir_path = self.prepare_dirs(parent_dir)
        log_name = "%s/%s" % (log_dir_path, f"{log_prefix}")
        # handler = logging.FileHandler(log_name)

        #
        handler = SafeLog(filename=log_name, when='H', interval=1, backupCount=100, encoding='utf-8')
        handler.suffix = "%Y-%m-%d-%H.log"

        handler.setFormatter(formatter)
        handler.setLevel('INFO')
        logger.addHandler(handler)

        # 输出到consloe
        chlr = logging.StreamHandler()
        chlr.setFormatter(formatter)
        chlr.setLevel('DEBUG')
        logger.addHandler(chlr)

        return logger


    def prepare_dirs(self, log_dir):
        log_dir_folder = os.path.exists(log_dir)
        if not log_dir_folder:
            os.makedirs(log_dir, mode=0o777)

        return log_dir
